/*
 * Copyright (C) 2011 mAPPn.Inc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mol.market.ui;

import android.app.LocalActivityManager;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.TabWidget;
import android.widget.TextView;

import com.mol.market.Constants;
import com.mol.market.R;
import com.mol.market.common.network.ApiAsyncTask.ApiRequestListener;
import com.mol.market.common.network.MarketAPI;
import com.mol.market.common.util.ImageUtils;
import com.mol.market.common.util.ThemeManager;
import com.mol.market.common.util.Utils;
import com.mol.market.common.vo.RecommendTopic;
import com.mol.market.common.widget.BaseTabActivity;
import com.mol.market.common.widget.MarqueeTextView;

/**
 * 玩家推荐详情页
 * 
 * @author andrew.wang
 * @date 2011-9-5
 * @since Version 0.8
 * 
 */
public class RecommendActivity extends BaseTabActivity implements OnClickListener,
        ApiRequestListener {

    private static final String TAB_ALL = "all";
    private static final String TAB_FOLLOWED = "followed";
    
    private TabHost mTabHost;
    private RecommendTopic mTopic;
    private CheckBox mFavorite;
    private boolean isFirstIn = true;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if(android.os.Build.VERSION.SDK_INT <= 11){
            this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        }

        setContentView(R.layout.activity_master_detail_layout);

        mTopic = (RecommendTopic) getIntent()
                .getSerializableExtra(Constants.EXTRA_RECOMMEND_DETAIL);

        initTopBar(mTopic);

        initTab();
        
        // 获取玩家评级
        MarketAPI.getMasterRecommendRating(getApplicationContext(), this, mTopic.id);
        // 获取关注状态
        MarketAPI.queryFoolowStatus(getApplicationContext(), this, mTopic.id);
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        LocalActivityManager lam = getLocalActivityManager();
        lam.removeAllActivities();
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {

        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            // 2011/10/19 修复点击Back多余操作的Bug
            Intent i = new Intent();
            i.putExtra(Constants.EXTRA_RECOMMEND_DETAIL, mTopic);
            setResult(RESULT_OK, i);
        }
        return super.dispatchKeyEvent(event);
    }

    /*
     * 初始化顶部栏
     */
    private void initTopBar(RecommendTopic topic) {
        
        TextView bg = (TextView) findViewById(R.id.topbar);
        bg.setBackgroundResource(ThemeManager.getResource(mSession, ThemeManager.KEY_TOP_BAR_BG));

        final ImageView ivIcon = (ImageView) findViewById(R.id.iv_user_icon);
        ImageUtils.download(getApplicationContext(), topic.icon, ivIcon,
                R.drawable.default_user_big, true, false);

        final MarqueeTextView title = (MarqueeTextView) findViewById(R.id.tv_name);
        title.setTextAppearance(getApplicationContext(),
                ThemeManager.getResource(mSession, ThemeManager.KEY_TOP_TITLE_TEXT));
        if (mSession.getTheme() == ThemeManager.THEME_TYPE_DARK) {
            title.setShadowLayer(0.1f, 0, -2.0f, Color.BLACK);
        }
        title.setText(topic.title);

        mFavorite = (CheckBox) findViewById(R.id.btn_operation);
        mFavorite.setButtonDrawable(ThemeManager.getResource(mSession,
                ThemeManager.KEY_TOP_BAR_FOLLOW));
        mFavorite.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                if (isFirstIn) {
                    return;
                }

                if (isChecked) {
                    Utils.trackEvent(getApplicationContext(), Constants.GROUP_4,
                            Constants.EVENT_CLICK_FOLLOW);
                    MarketAPI.requestFollowMaster(getApplicationContext(), RecommendActivity.this,
                            mTopic.id, "1");
                } else {
                    Utils.trackEvent(getApplicationContext(), Constants.GROUP_4,
                            Constants.EVENT_CLICK_UNFOLLOW);
                    MarketAPI.requestFollowMaster(getApplicationContext(), RecommendActivity.this,
                            mTopic.id, "0");
                }
                buttonView.setEnabled(false);
            }
        });
    }
    
    /*
     * 初始化Tab页面
     */
    private void initTab() {

        mTabHost = getTabHost();
        TabWidget widget = mTabHost.getTabWidget();
        widget.setPadding(mSession.mTabMargin110, 0, mSession.mTabMargin9, 0);
        mTabHost.setup();
        FrameLayout fl = (FrameLayout) mTabHost.findViewById(R.id.tab_frame_layout);
        fl.setBackgroundResource(ThemeManager.getResource(mSession, ThemeManager.KEY_TAB_BG));

        TabSpec tab1 = mTabHost.newTabSpec(TAB_ALL);
        tab1.setIndicator(Utils.createTabView(getApplicationContext(), mSession, 
                getString(R.string.recommendation_detail), -1, null));
        Intent i1 = new Intent(this, RecommendAppsActivity.class);
        i1.putExtra(Constants.EXTRA_RECOMMEND_DETAIL, mTopic);
        tab1.setContent(i1);
        mTabHost.addTab(tab1);

        TabSpec tab2 = mTabHost.newTabSpec(TAB_FOLLOWED);
        tab2.setIndicator(Utils.createTabView(getApplicationContext(), mSession, 
                getString(R.string.recommendation_comment), 1, null));
        Intent i2 = new Intent(this, RecommendDiscussActivity.class);
        i2.putExtra(Constants.EXTRA_RECOMMEND_DETAIL, mTopic);
        tab2.setContent(i2);
        mTabHost.addTab(tab2);

        mTabHost.setCurrentTab(0);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
        case R.id.btn_operation:
            MarketAPI.requestFollowMaster(getApplicationContext(), this, mTopic.id, "1");
            break;

        default:
            break;
        }
    }

    @Override
    public void onSuccess(int method, Object obj) {

        if (method == MarketAPI.ACTION_FOLLOW_MASTER) {

            mFavorite.setEnabled(true);

            Boolean result = (Boolean) obj;
            mFavorite.setChecked(result);

            if (isFirstIn) {
                // 首次进入此页面， 刷新关注状态，避免提醒
                isFirstIn = false;
                return;
            }
            if (result) {
                Utils.makeEventToast(getApplicationContext(),
                        getString(R.string.alert_follow_success), false);
            } else {
                Utils.makeEventToast(getApplicationContext(),
                        getString(R.string.alert_unfollow_success), false);
            }
        }
    }

    @Override
    public void onError(int method, int statusCode) {

        if (method == MarketAPI.ACTION_FOLLOW_MASTER) {
            mFavorite.setEnabled(true);
        }
        Utils.makeEventToast(getApplicationContext(), getString(R.string.alert_dialog_error), false);
    }

}
